import { useEffect, useState } from "react";
import { to } from "wsp-toolkit";

/**
 * @param reqFn {() => Promise<any>}
 * @param opts {{
 *   defaultData?: any;
 *   initLoading?: boolean;
 *   manual?: boolean;
 *   onSuccess?: (resp: any) => void;
 *   onFail?: (err: Error) => void;
 * }}
 * @returns {{data: undefined, loading: boolean, error: unknown}}
 */
export function useRequest(reqFn, opts = {}) {
  const {
    defaultData,
    initLoading = false,
    manual = false,
    onSuccess = () => {},
    onFail = () => {},
  } = opts;

  const [loading, setLoading] = useState(initLoading);
  const [error, setError] = useState(null);
  const [data, setData] = useState(defaultData);

  async function run() {
    if (typeof reqFn !== "function") {
      throw new TypeError("参数1需要是function");
    }
    setLoading(true);
    const [err, res] = await to(reqFn());
    setLoading(false);
    if (err) {
      setError(err);
      onFail(err);
      return;
    }
    setData(res);
    onSuccess(res);
  }

  useEffect(() => {
    if (manual) return;
    run();
  }, []);

  return {
    loading,
    error,
    data,
    run,
  };
}
